<template>
  <view class="pay-page">
    <view class="pay-info">
      <view class="pay-time-box">
        <text class="pay-time-tit">剩余支付时间：</text><text class="pay-time">{{ countdown }}</text>
      </view>
      <view class="pay-money">
        <text>支付金额：</text><text class="pay-mon">{{ paymentAmount }} </text><text>元</text>
      </view>
    </view>
    <view class="payment-methods">
      <view v-for="(method, index) in paymentMethods" :key="index" class="method-item"
        :class="{ active: selectedMethod === method }" @tap="selectPaymentMethod(method)">
        <image :src="method.logo" mode="aspectFit" class="method-logo" />
        <view class="method-details">
          <text class="method-name">{{ method.name }}</text>
          <text class="method-description">{{ method.description }}</text>
        </view>
      </view>
    </view>
    <button class="pay-button" @tap="initiatePayment" :disabled="submitStatus">立即支付</button>
  </view>
</template>

<script setup>
  import {
    ref,
    onMounted,
    computed
  } from 'vue';

  let orderId = ''; // 订单ID
  const paymentAmount = ref(0); // 支付金额
  let orderCreateTime = null; // 订单创建时间，这里应从后端获取
  const countdown = ref(''); // 倒计时显示
  const paymentMethods = ref([

    {
      logo: "../../static/images/icon/balance-pay.png", // 假定的微信支付图标路径
      name: '余额支付',
      type: 'balance',
      description: '使用账户余额支付'
    },
    {
      logo: "../../static/images/icon/wx.png", // 假定的微信支付图标路径
      name: '微信支付',
      type: 'wechat',
      description: '安全便捷的移动支付方式'
    },
    {
      logo: '../../static/images/icon/zfb.png', // 假定的支付宝图标路径
      name: '支付宝',
      type: 'alipay',
      description: '全球领先的第三方支付平台'
    },
    {
      logo: "../../static/images/icon/success-pay.png", // 假定的微信支付图标路径
      name: '测试支付',
      type: 'testPay',
      description: '测试支付，只为测试准备！'
    },
  ]);
  const selectedMethod = ref(null);
  let countdownInterval = null;
  const submitStatus = ref(false);

  onLoad((options) => {
    console.log(options);
    orderId = options.orderId;
    console.log(orderId);
  });

  onShow(() => {
    getOrderInfo()
  })

  // 倒计时逻辑
  const startCountdown = () => {
    // 获取订单创建时间与当前时间的差值（以毫秒为单位）
    const currentTime = new Date();
    const diff = orderCreateTime.getTime() + (15 * 60 * 1000) - currentTime.getTime(); // 15分钟倒计时，加上订单创建时间的15分钟

    if (diff <= 0) {
      countdown.value = '支付时间已过期';
      submitStatus.value = true;
      return;
    }

    let timeLeft = Math.ceil(diff / 1000); // 转换为秒，并向上取整，确保倒计时准确
    const timer = setInterval(() => {
      if (timeLeft <= 0) {
        clearInterval(timer);
        countdown.value = '支付时间已过期';
      } else {
        const minutes = Math.floor(timeLeft / 60);
        const seconds = timeLeft % 60;
        countdown.value = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
        timeLeft -= 1;
      }
    }, 1000);
  };

  //获取订单信息
  const getOrderInfo = async () => {
    http.request({
      url: '/orders/payInfo/' + orderId,
      method: 'GET',
      data: {
        orderId: orderId
      }, // 替换为实际的订单ID
    }).then(res => {
      console.log("订单信息");
      console.log(res)
      // 处理订单信息
      if (res.code == 0) {
        uni.showToast({
          icon: 'error',
          title: res.msg
        })
      } else {
        paymentAmount.value = res.data.totalPrice;
        console.log(res.data.createTime);
        orderCreateTime = new Date(res.data.createTime);
        console.log("订单金额" + paymentAmount.value);
        console.log(orderCreateTime);
        console.log(typeof orderCreateTime, orderCreateTime);
        startCountdown()
      }
    }).catch(res => {
      console.log("错误信息");
      console.log(res)
      if (res.code == 0) {
        uni.showToast({
          icon: 'error',
          title: res.msg
        })
      }
    })
  };

  const selectPaymentMethod = (method) => {
    selectedMethod.value = method;
  };

  const initiatePayment = async () => {
    console.log(selectedMethod.value);
    console.log("支付方式");
    console.log(selectedMethod.value.type);
    //检查是否选择了支付方式
    if (!selectedMethod.value) {
      uni.showToast({
        title: '请选择支付方式',
        icon: 'none'
      });
      return;
    }
    http.request({
        url: '/orders/pay',
        method: 'POST',
        data: {
          ordersId:orderId,
          payType: selectedMethod.value.type
        }
      }).then(res => {
        console.log("发起支付");
        console.log(res)
        if (res.code == 1) {
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          });
          // 支付成功后，可以跳转到订单详情页面
          uni.reLaunch({
            url: '/pages/pay-result/pay-result?sts=1&orderNumbers=' + orderId
          });
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      })
      .catch(res => {
        console.log("错误信息");
        console.log(res)
          uni.showToast({
            icon: 'error',
            title: res.msg
          })
      })

  };
</script>

<style scoped>
  .pay-page {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .pay-time-box {
    font-size: 18px;
    fwont-weight: bold;
    align-items: center;
    margin-bottom: 20px;
  }

  .pay-time-tit {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;
  }

  .pay-time {
    font-size: 20px;
    font-weight: bold;
    color: red;
  }

  .pay-money {
    font-weight: bold;
    color: #333;
    text-align: center;
    margin: 10px 0;
  }

  .pay-info {
    margin-bottom: 20px;
  }

  .pay-mon {
    font-size: 24px;
    font-weight: bold;
    color: #333;
    padding: 0 20px 0 15px;

  }

  .payment-methods {
    display: flex;
    flex-direction: column;
    /* 修改为垂直排列 */
    align-items: stretch;
    /* 使子元素撑满容器宽度 */
    width: 100%;
    margin-bottom: 30px;
  }

  .method-item {
    display: flex;
    flex-direction: row;
    /* 改为横向排列 */
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #ddd;
    /* 添加分割线 */
  }

  .method-item.active {
    background-color: #f0f8ff;
    /* 或其他颜色，表示选中状态 */
    border-left: 4px solid #007aff;
    /* 左侧添加一条蓝色边框表示选中 */
  }

  .method-logo {
    width: 60px;
    height: 60px;
    margin-right: 15px;
    margin-bottom: 10px;
  }

  .method-details {
    text-align: center;
  }

  .method-name {
    display: block;
    font-size: 20px;
    text-align: start;
    font-weight: bold;
    margin-bottom: 5px;
  }

  .method-description {
    color: #666;
  }

  .pay-button {
    width: 80%;
    height: 50px;
    line-height: 50px;
    background-color: #007aff;
    color: white;
    border-radius: 5px;
  }

  .pay-result {
    margin-top: 20px;
    font-size: 18px;
    color: green;
  }
</style>
